//
//  BPLoginViewController.m
//  BabyPhotograph
//
//  Created by cesh on 2017/2/4.
//  Copyright © 2017年 cesh. All rights reserved.
//

#define COUNTDOWN 5

#import "BPLoginViewController.h"
#import "BPAccountSettingViewController.h"

@interface BPLoginViewController ()
@property (weak, nonatomic) IBOutlet UIView *view1;
@property (weak, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UIButton *passwordBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) NSTimer *timer;
@property (assign, nonatomic) NSInteger countDownNo;

@end

@implementation BPLoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.alpha = 1.0;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.alpha = 1.0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    
    self.countDownNo = COUNTDOWN;
    
    UITapGestureRecognizer *tapOnBg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignKeyboard)];
    [self.view addGestureRecognizer:tapOnBg];
    
    self.view1.layer.cornerRadius = 8.0;
    self.view2.layer.cornerRadius = 8.0;
    self.loginBtn.layer.cornerRadius = 8.0;
    
    [self.passwordBtn addTarget:self action:@selector(clickPasswordBtn) forControlEvents:UIControlEventTouchUpInside];
}

- (void)clickPasswordBtn {
    //拦截电话号码空输入
    if(self.phoneTextField.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请先输入电话号码"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    [self.passwordBtn setTitle:[NSString stringWithFormat:@"等待(%li)", self.countDownNo--] forState:UIControlStateNormal];
    [self.passwordBtn setTitleColor: [UIColor colorWithRed:185/255.0 green:198/255.0 blue:208/255.0 alpha:1/1.0] forState:UIControlStateNormal];
    
    self.passwordBtn.enabled = NO;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self.passwordBtn setTitle:[NSString stringWithFormat:@"等待(%li)", self.countDownNo--] forState:UIControlStateNormal];
        if (self.countDownNo < 0) {
            self.countDownNo = COUNTDOWN;
            [self.passwordBtn setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
            [self.passwordBtn setTitleColor:[UIColor colorWithRed:118/255.0 green:177/255.0 blue:253/255.0 alpha:1/1.0] forState:UIControlStateNormal];
            self.passwordBtn.enabled = YES;
            [timer invalidate];
        }
    }];
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    
    [mgr POST:[NSString stringWithFormat:@"%@?c=Code&&a=send",requestURL]
   parameters:@{@"phone" : self.phoneTextField.text,
                @"sendType" : @"1"}
     progress:^(NSProgress * _Nonnull uploadProgress) {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             [SVProgressHUD showInfoWithStatus:responseObject[@"data"]];
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [SVProgressHUD dismiss];
             });
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [SVProgressHUD showInfoWithStatus:@"网络问题"];
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [SVProgressHUD dismiss];
         });
     }];
}

- (void)resignKeyboard {
    [self.phoneTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}

- (IBAction)loginBtn:(id)sender {
    [SVProgressHUD showWithStatus:@"登录中..."];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    
    [mgr POST:[NSString stringWithFormat:@"%@?c=User&&a=login",requestURL]
   parameters:@{@"phone" : self.phoneTextField.text,
                @"code" : self.passwordTextField.text}
     progress:^(NSProgress * _Nonnull uploadProgress) {
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
             NSLog(@"%@", responseObject[@"data"]);
             //记录下已登录的状态
             [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"login"];
             //保存用户基本信息
             [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"data"] forKey:@"user"];       
             //发送通知，更改左侧控制器的头像和昵称
             [SVProgressHUD dismiss];
             [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUserNickname" object:responseObject[@"data"][@"nickname"]];
             [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUserHeader" object:responseObject[@"data"][@"imgs"][0]];

             [self.navigationController popToRootViewControllerAnimated:YES];
         }
         else {
             [SVProgressHUD showWithStatus:responseObject[@"data"]];
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [SVProgressHUD dismiss];
             });
         }
        
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [SVProgressHUD showInfoWithStatus:@"网络问题"];
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [SVProgressHUD dismiss];
         });
     }];
    
}

@end
